<?php
namespace froyo\cherry\Base;


class Event extends BaseObject{

	public $handled;//是否处理
	public $name;//事件名
	public $data;//数据
	public $sender;//事件触发者

	protected static $_events = [];


	//事件解除
	public static function offEvent($class,$name){
		$class = ltrim($class, '\\');
        if (empty(self::$_events[$name][$class])) {
            return false;
        }
        if ($handler === null) {
            unset(self::$_events[$name][$class]);
            return true;
        }

        // plain event names
        if (isset(self::$_events[$name][$class])) {
            $removed = false;
            foreach (self::$_events[$name][$class] as $i => $event) {
                if ($event[0] === $handler) {
                    unset(self::$_events[$name][$class][$i]);
                    $removed = true;
                }
            }
            if ($removed) {
                self::$_events[$name][$class] = array_values(self::$_events[$name][$class]);
                return $removed;
            }
        }
        return $removed;
	}

	//事件绑定
	public static function onEvent($class,$name,$handler,$append=true){
		$class = ltrim($class, '\\');
		if(!isset(self::$_events[$name]))
		{
			self::$_events[$name] = [];
		}
        if ($append || empty(self::$_events[$name][$class])) {
            self::$_events[$name][$class][] = [$handler, $data];
        } else {
            array_unshift(self::$_events[$name][$class], [$handler, $data]);
        }
	}

	public static function hasHandlers($class,$name){
		$class = ltrim($class, '\\');
		if(!isset(self::$_events[$name]))
		{
			return false;
		}
		if(!isset(self::$_events[$name][$class]))
		{
			return false;
		}
		return true;
	}

	//触发事件
	public static function trigger($class,$name,$event){
        if (empty(self::$_events[$name])) {
            return;
        }

        if ($event === null) {
            $event = new static();
        }
        $event->handled = false;
        $event->name = $name;

        if (is_object($class)) {
            if ($event->sender === null) {
                $event->sender = $class;
            }
            $class = get_class($class);
        } else {
            $class = ltrim($class, '\\');
        }

        $classes = array_merge(
            [$class],
            class_parents($class, true),
            class_implements($class, true)
        );

        foreach ($classes as $class) {
            $eventHandlers = [];
            if (!empty(self::$_events[$name][$class])) {
                $eventHandlers = array_merge($eventHandlers, self::$_events[$name][$class]);
            }

            foreach ($eventHandlers as $handler) {
                $event->data = $handler[1];
                call_user_func($handler[0], $event);
                if ($event->handled) {
                    return;
                }
            }
        }

	}

}